package com.dex4d.ui.mine.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.dex4d.BuildConfig;
import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestParam;
import com.dex4d.model.User;
import com.dex4d.utils.Arith;
import com.dex4d.utils.BaseUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by chengyuchun on 2018/11/6.
 */
public class AuthorityReferralActivity extends AppToolBarBaseActivity {

    @BindView(R.id.tv_dex4d_balance)
    TextView tv_dex4d_balance;

    @BindView(R.id.tv_eth_balance)
    TextView tv_eth_balance;

    @BindView(R.id.progress_bar)
    ProgressBar progress_bar;

    @BindView(R.id.tv_position)
    TextView tv_position;

    @BindView(R.id.btn_referral)
    Button btn_referral;

    @BindView(R.id.tv_authority_describe)
    TextView tv_authority_describe;

    @BindView(R.id.ll_pay)
    LinearLayout ll_pay;

    @BindView(R.id.tv_pay_result)
    TextView tv_pay_result;

    @BindView(R.id.btn_pay)
    Button btn_pay;

    protected String mEthBalance;
    @Override
    protected void initToolbar() {
        showTitle(getString(R.string.referral));
        showBackView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_authority_referral;
    }

    @Override
    protected void initVariables() {
        btn_pay.setText(getString(R.string.pay_some_eth,"0.5"));
    }

    @Override
    protected void loadData() {
        queryAuth(IConstants.CONTRACTSERVICE_ISREFERRALER); //查询推荐权限
        queryEthBalance(); //查询以太余额
    }

    /**
     * 查询是否有权限
     * @param authType 权限类型
     */
    protected void queryAuth(String authType){
        RequestParam requestParam = new RequestParam();
        requestParam.setId(3);
        requestParam.setMethod(authType);
        requestParam.setParams(Collections.singletonList(User.getInstance().getAddress()));
        JsonApiWrapper
                .serviceApi()
                .requestByParam(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, true) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        queryDex4dBalance(result.getResult());
                    }});
    }

    //查询Dex4D余额
    protected void queryDex4dBalance(final String authStatus){
        RequestParam requestParam = new RequestParam();
        requestParam.setId(1);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.CONTRACTSERVICE_ERC20BALANCE);
        List<String> paramsList = new ArrayList<String>();
        paramsList.add(BuildConfig.CONTRACT_DEX4D_PROTOCOL);
        paramsList.add(User.getInstance().getAddress());
        requestParam.setParams(paramsList);

        JsonApiWrapper
                .serviceApi()
                .requestByParam(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, true) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        String balance = BaseUtils.hexToEtherUnit(result.getResult()); //unit ether
                        loadView(authStatus,balance);
                    }});
    }

    //根据权限与余额加载referral页面
    protected void loadView(String authStatus,String dex4dBalance){
        tv_dex4d_balance.setText(getString(R.string.current_dex4d_amount,dex4dBalance));
        if(Arith.sub(Double.parseDouble(dex4dBalance),500.00)>0){
            tv_authority_describe.setText(getString(R.string.temporally_available)); //临时推荐权限
            progress_bar.setProgress(100);
            tv_position.setText(100+"%");
            btn_referral.setBackgroundResource(R.drawable.btn_blue_click);
            btn_referral.setTextColor(getResources().getColor(R.color.white));
            btn_referral.setClickable(true);
        }else{
            try{
                tv_authority_describe.setText(getString(R.string.not_available_currently)); //没有推荐权限
                int progress  = (int)(Arith.div(Double.parseDouble(dex4dBalance),500.00,2) * 100);
                progress_bar.setProgress(progress);
                tv_position.setText(progress+"%");
                btn_referral.setBackgroundResource(R.drawable.btn_blue_unclick_bg);
                btn_referral.setTextColor(getResources().getColor(R.color.gray_B7C5CA));
                btn_referral.setClickable(false);
            }catch (Exception e){

            }
        }

        if(authStatus.equals("1")){
            //对永久推荐权限
            tv_authority_describe.setText(getString(R.string.permanent_available)); //永久推荐权限
            btn_referral.setBackgroundResource(R.drawable.btn_blue_click);
            btn_referral.setTextColor(getResources().getColor(R.color.white));
            btn_referral.setClickable(true);

            tv_pay_result.setVisibility(View.VISIBLE);
            tv_pay_result.setText(getString(R.string.pay_some_eth_result));
            ll_pay.setVisibility(View.GONE);

        }else if(authStatus.equals("2")){
            //购买后处于pending状态
            tv_pay_result.setVisibility(View.VISIBLE);
            tv_pay_result.setText(getString(R.string.pay_some_eth_pending));
            ll_pay.setVisibility(View.GONE);
        }else {
            //没有永久推荐权限
            tv_pay_result.setVisibility(View.GONE);
            ll_pay.setVisibility(View.VISIBLE);
        }
    }

    //查询ETH余额
    protected void queryEthBalance(){
        RequestParam requestParam = new RequestParam();
        requestParam.setId(2);
        requestParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestParam.setMethod(IConstants.CONTRACTSERVICE_GETBALANCE);
        requestParam.setParams(Collections.singletonList(User.getInstance().getAddress()));

        JsonApiWrapper
                .serviceApi()
                .requestByParam(requestParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, true) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        String balance = BaseUtils.hexToEtherUnit(result.getResult()); //unit ether
                        mEthBalance = balance;
                        tv_eth_balance.setText(getString(R.string.available_wallet_amount,balance));
                    }});
    }

    @OnClick({R.id.btn_pay,R.id.btn_referral})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.btn_referral:
                openActivity(DisplayReferralCodeActivity.class);
                break;
            case R.id.btn_pay:
                if(!TextUtils.isEmpty(mEthBalance) && Double.parseDouble(mEthBalance)<0.5){
                    Toast.makeText(this,getString(R.string.eth_balance_remind),Toast.LENGTH_SHORT).show();
                    return;
                }
                openActivity(ReferralAliasActivity.class);
                break;
        }
    }
}
